<template>
  <div>
    <!-- 筛选条件 -->
    <el-row :gutter="20" class="gl_searchBox">
      <el-col :span="6" :lg="4">
        <p>机构类型</p>
        <el-select v-model="api_GET_CompetitionQO.DelegationTypeCode" size="mini" placeholder="请选择机构类型" filterable @change="getPageList()">
          <el-option v-for="item in dictAll.delegationType" :key="item.code" :value="item.code" :label="item.value" />
        </el-select>
      </el-col>
      <el-col :span="12" :lg="8">
        <p>提交时间</p>
        <el-date-picker
          v-model="filterGameDate"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 100%;"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          size="mini"
          @change="handleGameTimeChange"
        />
      </el-col>
      <el-col :span="6" :lg="4">
        <p>审核状态</p>
        <el-select v-model="api_GET_CompetitionQO.ApproveStatusCode" size="mini" placeholder="请选择赛事类型" filterable @change="getPageList()">
          <el-option v-for="item in dictAll.entryApproveStatus" :key="item.code" :value="item.code" :label="item.value" />
        </el-select>
      </el-col>
      <el-col :span="6" :lg="4">
        <p>机构名称</p>
        <el-input v-model="api_GET_CompetitionQO.Filter" placeholder="请输入名称" size="mini" clearable @change="getPageList()" />
      </el-col>
      <el-col :span="6" :lg="4" class="search_btn">
        <!-- 查询按钮 -->
        <el-button type="primary" size="mini" @click="getPageList()">{{ $t('button.query') }}</el-button>
      </el-col>
    </el-row>

    <!-- 赛事统计 -->
    <div class="game_amount gl_py_15 gl_clear">
      <div class="game_logo">
        <img :src="getStaticPhotoUrl(gameInfo.competition && gameInfo.competition.logoImage)" alt="">
      </div>
      <div class="game_message">
        <div class="game_name">{{ gameInfo.competition && gameInfo.competition.name }}</div>
        <el-tag class="gl_my_5" size="small">{{ gameInfo.competition && gameInfo.competition.type.name }}</el-tag>
        <div>
          <span class="game_item">
            比赛时间：
            {{ gameInfo.competition && gameInfo.competition.startTime && gameInfo.competition.startTime.substring(0, 10) }} ~             {{ gameInfo.competition && gameInfo.competition.endTime && gameInfo.competition.endTime.substring(0, 10) }}
          </span>
          <span class="game_item">
            参赛机构：{{ gameInfo.delegationCount }}
          </span>
          <span class="game_item">
            参赛运动员：{{ gameInfo.registerCount }}
          </span>
        </div>
      </div>
    </div>
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="团体报名" name="seqTeam">
        <el-button type="primary" :loading="btnLoading_info" size="mini" style="margin-bottom: 10px;float: right;" @click="exportInfo()">机构名称变更记录</el-button>
        <el-table v-loading="tableLoading" class="gl_mb_15 game_table_list" :data="tableData" stripe size="mini" style="width: 100%">
          <el-table-column type="index" label="序号" :width="50" align="center" />
          <el-table-column prop="name" label="参赛机构" :min-width="170" />
          <el-table-column prop="submitName" label="付费机构名称" :min-width="170" />
          <el-table-column label="机构类型" :width="180" align="center">
            <template slot-scope="{ row }">
              {{ row.organizationType }}
            </template>
          </el-table-column>
          <el-table-column prop="phoneNumber" label="联系方式" :width="120" align="center" />
          <el-table-column prop="registerCount" label="参报人数" :width="100" align="center" />
          <el-table-column prop="entryCount" label="参报人次" :width="100" align="center" />
          <!-- <el-table-column prop="name" label="参报项目" :min-width="220">
            <template slot-scope="{ row }">
              <span v-for="(item, index) in row.categories" :key="index">
                {{ item }}
                <span v-if="index !== row.categories.length - 1">、</span>
              </span>
            </template>
          </el-table-column> -->
          <el-table-column label="提交时间" :width="150" align="center">
            <template slot-scope="{ row }">
              {{ row.creatTime | formatDate('yyyy-MM-dd HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column label="审核状态" :width="100">
            <template slot-scope="{ row }">
              <template v-if="row.approval && row.approval.approveStatusCode === 'NotPaid'">
                <span class="gl_color_grey">
                  <i class="el-icon-remove" />
                  {{ row.approval && row.approval.approveStatus && row.approval.approveStatus.name }}
                </span>
              </template>
              <template v-if="row.approval && row.approval.approveStatusCode === 'NotApproved'">
                <span class="gl_color_warning">
                  <i class="el-icon-remove" />
                  {{ row.approval && row.approval.approveStatus && row.approval.approveStatus.name }}
                </span>
              </template>
              <template v-if="row.approval && row.approval.approveStatusCode === 'ApproveSuccess'">
                <span class="gl_color_success">
                  <i class="el-icon-success" />
                  {{ row.approval && row.approval.approveStatus && row.approval.approveStatus.name }}
                </span>
              </template>
              <template v-if="row.approval && row.approval.approveStatusCode === 'ApproveFailed'">
                <span class="gl_color_error">
                  <i class="el-icon-error" />
                  {{ row.approval && row.approval.approveStatus && row.approval.approveStatus.name }}
                </span>
              </template>
            </template>
          </el-table-column>
          <el-table-column fixed="right" :label="$t('table.actions')" align="left" :width="150">
            <template slot-scope="{ row }">
              <el-button size="mini" type="text" @click="openOrderDetail(row)">
                <span class="gl_color_primary">查看详情</span>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row style="text-align: center;" class="gl_pb_15">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :page-size="api_GET_CompetitionQO.MaxResultCount"
            :current-page="api_GET_CompetitionQO.Page"
            @size-change="changePageSize"
            @current-change="changePage"
          />
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="个人报名" name="seqInd">
        <el-table v-loading="tableLoading" class="gl_mb_15 game_table_list" :data="tableData" stripe size="mini" style="width: 100%">
          <el-table-column type="index" label="序号" :width="50" align="center" />
          <el-table-column prop="name" label="参报人" :min-width="170" />
          <el-table-column prop="phoneNumber" label="联系方式" :width="120" align="center" />
          <el-table-column prop="registerCount" label="参报人数" :width="100" align="center" />
          <el-table-column prop="entryCount" label="参报人次" :width="100" align="center" />
          <!-- <el-table-column prop="name" label="参报项目" :min-width="220">
            <template slot-scope="{ row }">
              <span v-for="(item, index) in row.categories" :key="index">
                {{ item }}
                <span v-if="index !== row.categories.length - 1">、</span>
              </span>
            </template>
          </el-table-column> -->
          <el-table-column label="提交时间" :width="150" align="center">
            <template slot-scope="{ row }">
              {{ row.creatTime | formatDate('yyyy-MM-dd HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column label="审核状态" :width="100">
            <template slot-scope="{ row }">
              <template v-if="row.approval && row.approval.approveStatusCode === 'NotPaid'">
                <span class="gl_color_grey">
                  <i class="el-icon-remove" />
                  {{ row.approval && row.approval.approveStatus && row.approval.approveStatus.name }}
                </span>
              </template>
              <template v-if="row.approval && row.approval.approveStatusCode === 'NotApproved'">
                <span class="gl_color_warning">
                  <i class="el-icon-remove" />
                  {{ row.approval && row.approval.approveStatus && row.approval.approveStatus.name }}
                </span>
              </template>
              <template v-if="row.approval && row.approval.approveStatusCode === 'ApproveSuccess'">
                <span class="gl_color_success">
                  <i class="el-icon-success" />
                  {{ row.approval && row.approval.approveStatus && row.approval.approveStatus.name }}
                </span>
              </template>
              <template v-if="row.approval && row.approval.approveStatusCode === 'ApproveFailed'">
                <span class="gl_color_error">
                  <i class="el-icon-error" />
                  {{ row.approval && row.approval.approveStatus && row.approval.approveStatus.name }}
                </span>
              </template>
            </template>
          </el-table-column>
          <el-table-column fixed="right" :label="$t('table.actions')" align="left" :width="150">
            <template slot-scope="{ row }">
              <el-button size="mini" type="text" @click="openOrderDetail(row)">
                <span class="gl_color_primary">查看详情</span>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row style="text-align: center;" class="gl_pb_15">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :page-size="api_GET_CompetitionQO.MaxResultCount"
            :current-page="api_GET_CompetitionQO.Page"
            @size-change="changePageSize"
            @current-change="changePage"
          />
        </el-row>
      </el-tab-pane>
    </el-tabs>

    <!-- 订单详情 -->
    <el-dialog
      class="gl_dialog_TitleLine"
      width="1200px"
      title=""
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <el-tabs v-model="activeNametwo" type="card" @tab-click="actother">
        <el-tab-pane label="订单审核" name="order">
          <div v-if="orderDetail.expenses && orderDetail.expenses.length" class="order_detail">
            <component
              :is="expensesTypeList[item.Code]"
              v-for="(item, index) in orderDetail.expenses"
              :key="index"
              :game-info="gameInfo"
              :data="item"
            />
            <el-row class="total_amount">
              <el-col :span="24" align="right">
                合计：
                <span class="price">{{ orderDetail.TotalAmount && orderDetail.TotalAmount / 100 }}</span> 元，
                支付：
                <span class="price">{{ orderDetail.PayAmount && orderDetail.PayAmount / 100 }}</span> 元
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
        <el-tab-pane v-if="activeName === 'seqTeam'" label="其他赛事人员" name="group">
          <el-table v-loading="groupLoading" :data="othertable" size="mini">
            <el-table-column type="index" width="50" label="序号" align="center" />
            <el-table-column prop="name" label="姓名" width="160" />
            <el-table-column prop="gender.name" label="性别" width="50" align="center" />
            <el-table-column prop="idCardNumber" label="证件号码" width="150" align="center" />
            <el-table-column prop="registerTagType.name" label="人员类型" align="center" />
          </el-table>
          <el-row class="gl_pt_20" style="text-align: center;">
            <el-pagination
              :current-page="groupForm.Page"
              :page-size="groupForm.MaxResultCount"
              :total="groupTotalPage"
              layout="total,sizes,prev,pager,next,jumper"
              :page-sizes="[10, 20, 30, 40]"
              @size-change="groupSizeChange"
              @current-change="groupPageIndexChange"
            />
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <div v-if="orderDetail.expenses && orderDetail.expenses.length && orderDetail.approveStatusCode !== 'NotPaid'" slot="footer">
        <el-button size="mini" type="primary" :disabled="orderDetail.approveStatusCode == 'ApproveFailed'" @click="openApproveOrder">审核</el-button>
      </div>
    </el-dialog>
    <!-- 审核 -->
    <el-dialog
      class="gl_dialog_TitleLine"
      width="520px"
      title="请确认审核状态"
      :visible.sync="approveDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <el-form
        ref="approveVO"
        :model="approveVO"
        label-width="80px"
        size="mini"
        @submit.native.prevent
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="审核状态">
              <el-select v-model="approveVO.approveStatus" placeholder="请选择审核状态" style="width: 100%;">
                <template v-for="item in dict.entryApproveStatus">
                  <el-option v-if="item.code === 'ApproveSuccess' || item.code === 'ApproveFailed'" :key="item.code" :value="item.code" :label="item.value" />
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="驳回原因">
              <el-input
                v-model="approveVO.approveRemark"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4}"
                placeholder="请输入驳回原因"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button size="mini" @click="approveDialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" :loading="approveBtnLoading" @click="approveOrder">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import { errorText } from '@/lib';
import {
  Api_GET_EventsManagementCompetitionEntryApprovalCompetitionEntryApprovalListQO,
  SiSTKWEventsManagementEntryApproveInput
} from '@/lib/form/game/swaggerForm';
import { api_GET_DownLoadFileAddHeader } from '@/extend/api/file';
import {
  api_GET_EventsManagemententrybyOtherPerson, // 查询运动员以外的报项人员
  api_GET_EventsManagementCompetitionEntryApprovalCompetitionEntryApprovalList,
  api_GET_EventsManagementCompetitionEntryApprovalCompetitionEntryApprovalSummaryCompetitionId,
  api_POST_EventsManagementEntryApproveCompetitionEntries
} from '@/extend/api/gameswaggerApi/app';
import entry from './expenses/entry';
import simultaneousEntry from './expenses/simultaneousEntry';
import deposit from './expenses/deposit';
import insurance from './expenses/insurance';
import custom from './expenses/custom';
import bigTeam from './expenses/bigTeam';
import foot from './expenses/foot';
import {
  Api_GET_EventsManagementEntryByPersonQO
} from '@/lib/form/game/swaggerForm';
export default {
  data() {
    return {
      btnLoading_info: false,
      othertable: [],
      groupLoading: false,
      filterGameDate: [],
      api_GET_CompetitionQO: new Api_GET_EventsManagementCompetitionEntryApprovalCompetitionEntryApprovalListQO(),
      tableData: [],
      total: 0,
      groupForm: new Api_GET_EventsManagementEntryByPersonQO(), // 查询团体报项单所用表单
      activeNametwo: 'order',
      tableLoading: false,
      gameInfo: {},
      activeName: 'seqTeam',
      dialogVisible: false,
      orderDetail: {},
      groupTotalPage: 0,
      expensesTypeList: {
        Entry: entry,
        SimultaneousEntry: simultaneousEntry,
        Deposit: deposit,
        Insurance: insurance,
        Custom: custom,
        BigTeam: bigTeam,
        Foot: foot
      },
      approveBtnLoading: false,
      approveDialogVisible: false,
      approveVO: new SiSTKWEventsManagementEntryApproveInput()
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      dictAll: state => state.dict.dictAll
    })
  },
  created() {
    this.gameId = this.$route.params.id;
    this.getDict();
    this.initForm();
    this.getGameDetail();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    initForm() {
      this.api_GET_CompetitionQO = new Api_GET_EventsManagementCompetitionEntryApprovalCompetitionEntryApprovalListQO();
      this.api_GET_CompetitionQO.IsDelegation = true;
      this.activeName = 'seqTeam';
      this.api_GET_CompetitionQO.CompetitionId = this.gameId;
      this.getPageList();
    },
    exportInfo() {
      const that = this;
      this.btnLoading_info = true;
      const tempUrl = `/api/excel`;
      const fileName = '机构名称变更记录' + '.xlsx';
      const code = WEB_CONFIG.VUE_APP_SWAGGER_GAME_BASE;
      const params = {};
      params.ReportName = 'DelegationNameChanged';
      params.GetCompetitionEntryApprovalsInput = JSON.stringify({ 'IsDelegation': true,'CompetitionId':this.api_GET_CompetitionQO.CompetitionId  });
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, params , code).then(res => {
        this.btnLoading_info = false;
      }).catch(error => {
        that.btnLoading_info = false;
        errorText(error).then(function(text) {
          that.$message({ type: 'error', message: text });
        });
      });
    },
    // 获取报项赛事详情
    getGameDetail() {
      api_GET_EventsManagementCompetitionEntryApprovalCompetitionEntryApprovalSummaryCompetitionId(this.gameId).then(res => {
        this.gameInfo = res || {};
      }, error => {
        this.$message({ type: 'error', message: error.error && error.error.message || '' });
      });
    },
    // 查询报项列表
    getPageList(page) {
      this.api_GET_CompetitionQO.Page = page || 1;
      this.api_GET_CompetitionQO.SkipCount = (this.api_GET_CompetitionQO.Page - 1) * this.api_GET_CompetitionQO.MaxResultCount;
      this.tableLoading = true;
      api_GET_EventsManagementCompetitionEntryApprovalCompetitionEntryApprovalList(this.api_GET_CompetitionQO).then(res => {
        this.tableLoading = false;
        this.tableData = res.items || [];
        this.total = res.totalCount;
        console.log(this.tableData);
      }, error => {
        this.tableLoading = false;
        this.$message({ type: 'error', message: error.error && error.error.message || '' });
      });
    },
    actother () {
      console.log('🚀 ~ file: approveDetail.vue:407 ~ actother ~ this.activeNametwo:', this.activeNametwo);
      if (this.activeNametwo === 'group') {
        this.getDetailGroup();
      }
    },
    getDetailGroup(page) {
      var that = this;
      that.groupLoading = true;
      that.groupForm.Page = page || 1;
      that.groupForm.SkipCount = (that.groupForm.Page - 1) * that.groupForm.MaxResultCount;
      that.groupForm.CompetitionId = that.orderDetail.competitionId;
      that.groupForm.DelegationId = that.orderDetail.Delegationld;
      // that.groupForm.CompEntryApproveStatusCode = that.groupApproveStatus.code;
      api_GET_EventsManagemententrybyOtherPerson(that.groupForm).then(res => {
        that.othertable = res.items;
        that.groupTotalPage = res.totalCount;
        that.groupLoading = false;
      }).catch(error => {
        that.groupLoading = false;
        this.$message({ type: 'error', message: error.error && error.error.message || '' });
      });
    },
    handleClick(val) {
      this.tableData = [];
      this.api_GET_CompetitionQO.MaxResultCount = 10;
      this.api_GET_CompetitionQO.IsDelegation = !!(val.name === 'seqTeam');
      this.getPageList();
    },
    openOrderDetail(entryInfo) {
      this.activeNametwo = 'order';
      const _detail = entryInfo.approval && entryInfo.approval.detail || '';
      this.orderDetail = this.handleOrderDetail(_detail);
      this.orderDetail.competitionEntryApprovalId = entryInfo.approval.id;
      this.orderDetail.approveStatusCode = entryInfo.approval.approveStatusCode;
      this.orderDetail.approveRemark = entryInfo.approval.approveRemark;
      this.orderDetail.competitionId = entryInfo.approval.competitionId;
      this.orderDetail.Delegationld = entryInfo.approval.entryScopeId;
      console.log(this.orderDetail);
      this.dialogVisible = true;
    },
    // 处理订单详情数据
    handleOrderDetail(detail) {
      if (!detail) return {};
      const _detail = JSON.parse(detail);
      const _summary = _detail.Summary || [];
      const _charges = _detail.Charges || [];
      _detail.expenses = [];
      for (let i = 0; i < _charges.length; i++) {
        let item = _charges[i];
        for (let j = 0; j < _summary.length; j++) {
          const jtem = _summary[j];
          if (jtem.ChargeTypeCode === item.Code) {
            item = { ...item, ...jtem };
            break;
          }
        }
        _detail.expenses.push(item);
      }
      return _detail;
    },
    // 团体报项单分页
    groupSizeChange(MaxResultCount) {
      this.groupForm.MaxResultCount = MaxResultCount;
      this.getDetailGroup();
    },
    groupPageIndexChange(currentPage) {
      this.getDetailGroup(currentPage);
    },
    openApproveOrder() {
      this.approveVO = new SiSTKWEventsManagementEntryApproveInput();
      if (this.orderDetail.approveStatusCode !== 'ApproveFailed' && this.orderDetail.approveStatusCode !== 'ApproveSuccess') {
        this.approveVO.approveStatus = 'ApproveSuccess';
      } else {
        this.approveVO.approveStatus = this.orderDetail.approveStatusCode || 'ApproveSuccess';
      }
      this.approveVO.competitionEntryApprovalId = this.orderDetail.competitionEntryApprovalId;
      this.approveVO.approveRemark = this.orderDetail.approveRemark || '';
      console.log(this.approveVO);
      this.approveDialogVisible = true;
    },
    // 审核
    approveOrder() {
      if (this.approveVO.approveStatus === 'ApproveFailed' && !this.approveVO.approveRemark) {
        this.$message({ type: 'error', message: '审核状态为审核不通过时，必须填写驳回原因' });
        return;
      }
      this.approveBtnLoading = true;
      api_POST_EventsManagementEntryApproveCompetitionEntries(this.approveVO).then(res => {
        this.$message({ type: 'success', message: '审核成功' });
        this.approveBtnLoading = false;
        this.approveDialogVisible = false;
        this.dialogVisible = false;
        this.getPageList(this.api_GET_CompetitionQO.Page);
      }, error => {
        this.approveBtnLoading = false;
        this.$message({ type: 'error', message: error.error && error.error.message || '' });
      });
    },
    // 处理时间筛选项
    handleGameTimeChange(time) {
      this.api_GET_CompetitionQO.StartTime = time && time[0];
      this.api_GET_CompetitionQO.EndTime = time && time[1];
      this.getPageList();
    },
    changePage(page) {
      this.getPageList(page);
    },
    changePageSize(pagesize) {
      this.api_GET_CompetitionQO.MaxResultCount = pagesize;
      this.getPageList();
    },
    getStaticPhotoUrl(relativeUrl) {
      if (relativeUrl) {
        return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
      } else {
        return require('@/assets/images/face_default.png');
      }
    }
  }
};
</script>
<style>
.game_amount .game_logo {
  float: left;
}
.game_amount .game_logo img {
  width: 74px;
  height: 74px;
  border-radius: 50%;
}
.game_amount .game_message {
  float: left;
  padding: 5px 20px;
  box-sizing: border-box;
  font-size: 14px;
}
.game_amount .game_name {
  font-weight: bold;
  font-size: 16px;
}
.game_amount .game_item {
  margin-right: 25px;
}
.charge_item_title {
  font-size: 16px;
  line-height: 24px;
  font-weight: bold;
}
.charge_item_amount {
  font-size: 14px;
  font-weight: normal;
}
.order_detail .el-table,
.order_detail .el-table .el-table__body-wrapper {
  min-height: auto;
}
.order_detail .get_money {
  display:inline-block;
  margin-left:120px;
  vertical-align: top;
}
.gl_dialog_TitleLine .el-dialog__header {
  border: 0px;
}
.order_detail .el-table {
  border: none;
  border-bottom: 1px solid #353434;
}
.order_detail .el-table th{
  border-right: none;
  background: #fafafa;
}
.order_detail .el-table td {
  border-right: none;
}
.order_detail .el-table .el-table__body-wrapper {
  min-height: auto;
}
.order_detail .table {
  border-right: none !important;
}
.total_amount {
  margin-top: 10px;
  font-weight: bold;
  font-size: 14px;
}
.total_amount .price {
  font-size: 20px;
  color: #E02020;
}
</style>
